'use strict';
/**
 * Created by FreezeSoul on 2015/11/4.
 */
define([
    'angular',
    'adConfig',
    'app/modules/index/define',
    'app/modules/page/services/page',
    'app/modules/folder/services/folder-tree',
    'app/modules/index/services/index'
], function (angular, adConfig) {
    angular.module('ad.index')
        .controller('adIndexSeriesEventController', ['$scope', '$uibModalInstance', '_', 'adFolderEditService', 'adPageEditService', 'adIndexEditService', 'item', 'current'
            , function ($scope, $uibModalInstance, _, folderService, pageService, service, item, current) {

                $scope.Item = item;
                $scope.current = current;
                $scope.isLoading = false;

                $scope.PageParams = [];

                $scope.isTreeLoading = true;

                $scope.treeOptions = {
                    nodeChildren: "children",
                    dirSelectable: false,
                    allowDeselect: false,
                    isSelectable: function (node) {
                        return node.type !== "folder";
                    },
                    injectClasses: {
                        "iExpanded": "glyphicon glyphicon-chevron-down",
                        "iCollapsed": "glyphicon glyphicon-chevron-right"
                    }
                };

                $scope.treeModels = [];

                $scope.expandedFolders = [];

                $scope.selected = undefined;

                $scope.itemSelected = function (node) {
                    $scope.PageParams = [];

                    $scope.isLoading = true;

                    $scope.Item.PageId = node.id;

                    if ($scope.Item.Params.length > 0) {
                        service.loadPageParams(node.id).then(function (data) {
                            var obj = angular.fromJson(data);
                            if (obj.result == 'success') {
                                $scope.PageParams = obj.data;
                                $scope.isLoading = false;
                            } else {
                                $scope.isLoading = false;
                            }
                        }, function () {
                            $scope.isLoading = false;
                        });
                    }
                };

                $scope.loadFolders = function () {
                    folderService.getFolders(adConfig.pageFolderType).then(function (data) {
                        var obj = angular.fromJson(data);
                        if (obj.result == 'success') {
                            var rootItemId = adConfig.rootFolderId;
                            var rootItem = {
                                "name": "页面根目录",
                                "id": rootItemId,
                                "type": "folder",
                                "data": {folder_id: rootItemId},
                                "children": [],
                                "parent": {}
                            };
                            $scope.expandedFolders.push(rootItem);
                            var convertFolderToTreeNode = function (currentParentId, parentFolderItem) {
                                var folders = _.filter(obj.data, function (item) {
                                    return item.folder_parent == currentParentId
                                });
                                folders = _.sortBy(folders, function (item) {
                                    return item.folder_name
                                });
                                _.each(folders, function (folder) {
                                    var currentId = folder.folder_id;
                                    var currentItem = {
                                        "name": folder.folder_name,
                                        "id": folder.folder_id,
                                        "type": "folder",
                                        "data": folder,
                                        "children": [],
                                        "parent": parentFolderItem
                                    };
                                    convertFolderToTreeNode(currentId, currentItem);
                                    parentFolderItem.children.push(currentItem);
                                });
                            };
                            convertFolderToTreeNode(rootItemId, rootItem);

                            $scope.loadPages(rootItem);
                        }
                    }, function () {
                    });
                };

                $scope.loadPages = function (rootItem) {
                    pageService.getPages().then(function (data) {
                        var obj = angular.fromJson(data);
                        if (obj.result == 'success') {
                            var walkThroughFolders = function (folder) {
                                var folderId = folder.id;
                                var pages = _.filter(obj.data, function (item) {
                                    return item.page_folder_id == folderId
                                });
                                _.each(pages, function (page) {
                                    page.page_home = page.page_home ? 1 : 0;
                                    var item = {
                                        "name": page.page_name,
                                        "id": page.page_id,
                                        "type": "element",
                                        "data": page,
                                        "children": [],
                                        "parent": folder
                                    };
                                    folder.children.push(item);
                                });
                                var childFolders = _.filter(folder.children, function (item) {
                                    return item.type == "folder"
                                });
                                _.each(childFolders, function (folder) {
                                    walkThroughFolders(folder);
                                });
                            };
                            walkThroughFolders(rootItem);

                            $scope.treeModels.push(rootItem);

                            $scope.isTreeLoading = false;

                            $scope.setCurrent();
                        }
                    });
                };

                $scope.hightlightSelected = function (pageId) {
                    var walkThroughFolders = function (currentItem) {
                        if (currentItem.type == "element" && currentItem.id == pageId) {
                            $scope.selected = currentItem;
                        } else {
                            var page = _.find(currentItem.children, function (item) {
                                return item.type == "element" && item.id == pageId
                            });
                            if (page) {
                                $scope.selected = page;
                            } else {
                                var childFolders = _.filter(currentItem.children, function (item) {
                                    return item.type == "folder"
                                });
                                _.each(childFolders, function (folder) {
                                    walkThroughFolders(folder);
                                })
                            }
                        }
                    };
                    if ($scope.treeModels.length == 1) {
                        walkThroughFolders($scope.treeModels[0]);
                    }
                    if (!$scope.selected) return;
                    var current = $scope.selected.parent;
                    while (current.id) {
                        if ($scope.expandedFolders.indexOf(current) == -1) {
                            $scope.expandedFolders.push(current);
                        }
                        current = current.parent;
                    }
                    $scope.itemSelected($scope.selected);

                };


                $scope.removeParamName = function (param) {
                    param.ParamName = "";
                };

                $scope.setCurrent = function () {
                    _.each($scope.Item.params, function (param) {
                        param.ParamName = "";
                    });
                    if ($scope.current) {
                        $scope.hightlightSelected($scope.current.PageId);
                        _.each($scope.Item.Params, function (p) {
                            var finded = _.findWhere($scope.current.Params, {Value: p.Value});
                            if (finded) {
                                p.ParamName = finded.ParamName;
                            }
                        });
                    }
                };

                $scope.ok = function () {
                    $uibModalInstance.close($scope.Item);
                };

                $scope.cancel = function () {
                    $uibModalInstance.dismiss('cancel');
                };

                $scope.clear = function () {
                    $uibModalInstance.close();
                };


                $scope.loadFolders();


            }]);
});